from flask import Flask, request, jsonify
import io
import contextlib
import subprocess
import os

app = Flask(__name__)


@app.route('/run', methods=['POST'])
def run_code():
    # 获取用户提交的代码
    code = request.json.get('code', '')

    # 将代码写入 tool_code.py 文件
    with open('tool_code.py', 'w', encoding='utf-8') as f:
        f.write(code)

    # 捕获 print 输出
    output = io.StringIO()
    try:
        with contextlib.redirect_stdout(output):  # 重定向 stdout 到 output
            # 执行 tool_code.py 文件
            result = subprocess.run(
                ['python', 'tool_code.py'],  # 执行命令
                text=True,                   # 以文本模式捕获输出
                capture_output=True,         # 捕获标准输出和标准错误
                check=True                   # 检查命令是否成功
            )
            result = result.stdout  # 获取标准输出
    except subprocess.CalledProcessError as e:
        result = f"Error: {e.stderr}"  # 捕获子进程错误
    except Exception as e:
        result = f"Error: {str(e)}"    # 捕获其他异常

    # 返回结果
    return jsonify({"output": result})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6677)
